package com.zhentao.repository;

import com.zhentao.entity.AiMessage;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI消息数据访问层
 */
@Repository
public interface AiMessageRepository extends MongoRepository<AiMessage, String> {
    
    /**
     * 根据会话ID分页查询消息
     */
    Page<AiMessage> findByConversationIdOrderByTimestampAsc(String conversationId, Pageable pageable);
    
    /**
     * 根据会话ID倒序查询消息
     */
    Page<AiMessage> findByConversationIdOrderByTimestampDesc(String conversationId, Pageable pageable);
    
    /**
     * 根据用户ID和会话ID查询消息
     */
    Page<AiMessage> findByUserIdAndConversationIdOrderByTimestampAsc(Integer userId, String conversationId, Pageable pageable);
    
    /**
     * 获取会话的最后一条消息
     */
    @Query(value = "{'conversationId': ?0}", sort = "{'timestamp': -1}")
    List<AiMessage> findTopByConversationIdOrderByTimestampDesc(String conversationId);
    
    /**
     * 统计会话的消息数量
     */
    long countByConversationId(String conversationId);
    
    /**
     * 统计用户在指定时间范围内的消息数量
     */
    @Query(value = "{'userId': ?0, 'timestamp': {$gte: ?1, $lte: ?2}}", count = true)
    long countByUserIdAndTimestampBetween(Integer userId, LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 根据会话ID删除所有消息
     */
    void deleteByConversationId(String conversationId);
    
    /**
     * 根据用户ID删除所有消息
     */
    void deleteByUserId(Integer userId);
    
    /**
     * 查找指定时间之前的消息（用于清理）
     */
    @Query("{'timestamp': {$lt: ?0}}")
    List<AiMessage> findMessagesOlderThan(LocalDateTime cutoffTime);
    
    /**
     * 根据消息类型统计数量
     */
    @Query(value = "{'conversationId': ?0, 'messageType': ?1}", count = true)
    long countByConversationIdAndMessageType(String conversationId, String messageType);
    
    /**
     * 查找会话中的系统消息
     */
    @Query("{'conversationId': ?0, 'isSystem': true}")
    List<AiMessage> findSystemMessagesByConversationId(String conversationId);
}
